import os

from alipay import AliPay
from django import http
from django.conf import settings
# Create your views here.
from django.views import View

from meiduo_mall.utils.response_code import RETCODE
from meiduo_mall.utils.view import LoginRequiredMixin
from orders.models import OrderInfo


class PaymentView(LoginRequiredMixin, View):
    def get(self, request, order_id):
        user = request.user
        try:
            order = OrderInfo.objects.get(order_id=order_id,
                                          user=user,
                                          status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'])
        except Exception as e:
            return http.HttpResponseForbidden('订单不存在')

        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/app_private_key.pem"),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                "keys/alipay_public_key.pem"),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )

        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            subject="美多商城%s" % order_id,
            return_url=settings.ALIPAY_RETURN_URL,
        )

        alipay_url = settings.ALIPAY_URL + "?" + order_string

        return http.JsonResponse({'code': RETCODE.OK,
                                  'errmsg': 'ok',
                                  'alipay_url': alipay_url})